package api

import (
	"context"
	"easyShop/core/database/elasticsearch"
	"easyShop/core/database/mysql"
	"easyShop/messageQueue/rabbit/producer"
	"easyShop/model"
	"easyShop/services"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"strconv"
)

type ProductController struct {
}

func (p ProductController) GetProductList(c *gin.Context) {
	search := c.Query("search")
	page, _ := strconv.Atoi(c.Query("page"))
	productList := services.GetProductList(search, page)
	c.JSON(200, gin.H{
		"code":    "200",
		"message": "success",
		"data":    productList,
	})
}

func (p ProductController) GetProductInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	producer.UpdateProductToEs(id)
	var getEsErr error
	var productInfo model.Product
	productInfo, getEsErr = services.GetProductInfoFromEs(uint(id))
	// 如果读取es失败则去查db
	if getEsErr != nil {
		var getDbErr error
		productInfo, getDbErr = services.GetProductInfo(uint(id))
		if getDbErr != nil {
			c.JSON(200, gin.H{
				"code":    "500",
				"message": getDbErr.Error(),
				"data":    []string{},
			})
			return
		}
		// 写入数据到es
		services.SetProductInfoToEs(productInfo)
	}

	c.JSON(200, gin.H{
		"code":    "200",
		"message": "success",
		"data":    productInfo,
	})
}

func (p ProductController) BatchCreateProduct(c *gin.Context) {
	var productList []model.Product

	for i := 0; i < 1000; i++ {
		product := model.Product{}
		product.Name = "商品名称_" + strconv.Itoa(i)
		product.Price = 1 + float32(i)
		product.Stock = 1 + i
		product.Description = "商品描述_" + strconv.Itoa(i)
		product.Detail = "商品详情_" + strconv.Itoa(i)

		productList = append(productList, product)
	}

	dbConn := mysql.GetConnect()
	dbConn.Create(productList)

	esConn, _ := elasticsearch.GetConnect()
	bulk := esConn.Bulk()
	for _, product := range productList {
		productInfoByte, _ := json.Marshal(product)
		request := elastic.NewBulkIndexRequest().
			Index("product").
			Id(strconv.Itoa(int(product.Id))).
			Type("_doc").
			Doc(string(productInfoByte))
		bulk = bulk.Add(request)

	}

	bulkRes, err := bulk.Do(context.Background())

	if err != nil {
		fmt.Print("\n写入Es错误\n")
	}

	fmt.Print("\n bulkRes=", bulkRes)

}
